package com.example.rustfs.dao;

import com.example.rustfs.entity.DeletedFile;
import org.springframework.stereotype.Repository;

import java.time.LocalDateTime;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 回收站数据访问层
 */
@Repository
public class RecycleBinDao {
    
    private final Map<Long, DeletedFile> deletedFiles = new ConcurrentHashMap<>();
    private final AtomicLong idGenerator = new AtomicLong(1);
    
    public DeletedFile save(DeletedFile file) {
        if (file.getId() == null) {
            file.setId(idGenerator.getAndIncrement());
        }
        deletedFiles.put(file.getId(), file);
        return file;
    }
    
    public List<DeletedFile> findByUserId(Long userId) {
        return deletedFiles.values().stream()
                .filter(f -> f.getUserId().equals(userId))
                .filter(f -> f.getExpireTime().isAfter(LocalDateTime.now()))
                .sorted(Comparator.comparing(DeletedFile::getDeletedTime).reversed())
                .collect(Collectors.toList());
    }
    
    public DeletedFile findById(Long id) {
        return deletedFiles.get(id);
    }
    
    public void delete(Long id) {
        deletedFiles.remove(id);
    }
    
    public void deleteByUserId(Long userId) {
        deletedFiles.values().removeIf(f -> f.getUserId().equals(userId));
    }
    
    /**
     * 清理过期文件
     */
    public List<DeletedFile> findExpiredFiles() {
        LocalDateTime now = LocalDateTime.now();
        return deletedFiles.values().stream()
                .filter(f -> f.getExpireTime().isBefore(now))
                .collect(Collectors.toList());
    }
}

